<?php

class AdminController extends BaseController
{

    /**
     * Declares class-based actions.
     */
    public function AdminController()
    {
        ///layout admin
        $this->layout = '//layouts/admin';
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('LayDuLieuLoDe', 'layketquaxosotudong', 'ThongKeDanhSachThangGameLode'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform
                'actions' => array('index', 'bomb', 'blackorwhite', 'luckytrain', 'news', 'newsdetail', 'users', 'editusers', 'layketquaxoso', 'lode',
                'nhapketqualode'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/admin.php'

        $data['name'] = "HHT";
        $data['age'] = 23;
        $data['email'] = "0987120690@yahoo.com";
        $this->render('backend/admin/index', $data);
    }

    public function actionLogout()
    {
        $_SESSION['isdangnhap'] = false;
        $this->redirect(Yii::app()->request->baseUrl.'/index.php/backend/admin/login');
    }

    public function actionLogin()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/admin.php'
        $data = array();
        $user = 'admin';
        $pass = 'admin';
        if (isset($_POST['btn_login']))
        {
            $g_user = $_POST['username'];
            $g_pass = $_POST['password'];
            if ($g_user == $user && $g_pass == $pass)
            {
                //dang nhap thanh cong
                Yii::app()->session->open();
                Yii::app()->session['isdangnhap'] = true;
                $_SESSION['isdangnhap'] = true;
                $this->redirect(Yii::app()->request->baseUrl.'/index.php/backend/admin');
            }
            else
            {
                $data['error'] = '<span style="color:red;font-weight:bold">Nhập lại chính xác username và  password!</span>';
            }
        }
        $this->layout = 'n';
        $this->render('backend/admin/login', $data);
    }

    //Game bomb
    public function actionBomb()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="bomb_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'bomb_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/bomb_setting', $data);
    }

    //Black or White
    public function actionBlackorWhite()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="blackorwhite_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'blackorwhite_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/blackorwhite_setting', $data);
    }

    //Lucky train
    public function actionLuckytrain()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="luckytrain_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'luckytrain_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/luckytrain_setting', $data);
    }

    //List news
    public function actionNews()
    {
        $data = array();
        //load data
        $list_news = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_news')
                ->queryAll();
        $data['list_news'] = $list_news;
        $this->render('backend/admin/infonews', $data);
    }

    //News detail
    public function actionNewsdetail()
    {
        $data = array();

        if (isset($_GET['id']))
        {
            $id = $_GET['id'];
            //load data
            $news_detail = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_news')
                    ->where('id=:id', array(':id' => $id))
                    ->queryRow();
            //get data
        }
        else
        {
            $this->redirect(Yii::app()->request->baseUrl.'/index.php/backend/admin/news');
        }

        //save
        if (isset($_POST['btn_changerule']))
        {
            $news = array();
            $id = $_GET['id'];
            $news['title'] = $_POST['txtTitle'];
            $news['content'] = $_POST['textarea_id'];
            Yii::app()->db->createCommand()
                    ->update('ld_news', $news, 'id='.$id);
            $this->redirect(Yii::app()->request->baseUrl.'/index.php/backend/admin/news');
        }

        $data['news_detail'] = $news_detail;
        $this->render('backend/admin/newsdetail', $data);
    }

    //user
    public function actionUsers()
    {
        $data = array();
        $user = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_user')
                ->queryAll();
        $data['users'] = $user;
        $this->render('backend/admin/user', $data);
    }

    //user
    public function actionEditusers()
    {
        //http://localhost/lode/index.php/backend/admin/Editusers?id=1
        if (isset($_GET['id']))
        {
            $data = array();
            $id = $_GET['id'];
            if (isset($_POST['btnban']))
            {
                $edituser = array();
                $edituser['active'] = 2;
                Yii::app()->db->createCommand()
                        ->update('ld_user', $edituser, 'user_id='.$id);
            }

            if (isset($_POST['btnunban']))
            {
                $edituser = array();
                $edituser['active'] = 1;
                Yii::app()->db->createCommand()
                        ->update('ld_user', $edituser, 'user_id='.$id);
            }

            $user = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_user')
                    ->where('user_id=:id', array(':id' => $id))
                    ->queryRow();
            $data['user'] = $user;
            $this->render('backend/admin/edituser', $data);
        }
        else
        {
            $this->redirect(Yii::app()->request->baseUrl.'/index.php/backend/admin/users');
        }
    }

    public function actionLayKetQuaXoSo()
    {
        $today = (isset($_POST['date']) && $_POST['date'] !== '') ? $_POST['date'] : '';
        
        if($today !== '')
        {
            $tmp = explode('-', $today);
            $today = join('/', array_reverse($tmp));
        }
        else
        {
            $today = date('d/m/Y');
        }
        echo '<strong>Kết quả xổ số ngày: '.$today.'</strong>';
        //die;
        /*
          // Initialize the curl object
          $curl = curl_init();

          curl_setopt($curl, CURLOPT_URL, "http://www.xosothudo.com.vn/jquery/?option=com_main");
          curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

          $data = array(
          'results_date' => $today
          );

          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($curl, CURLOPT_POST, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

          $response = curl_exec($curl);
          curl_close($curl);
         */

        $postdata = http_build_query(
                array(
                    'results_date' => $today,
                )
        );

        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($opts);

        $response = file_get_contents('http://www.xosothudo.com.vn/jquery/?option=com_main', false, $context);

        $post = strrpos($response, "<table");

        if ($post)
        {
            $response = substr($response, $post);
            preg_match_all('/(<td>|<td style=(.*?)>)(.*?)<\/td>/', $response, $matches);
            $this->renderPartial('backend/admin/ketquaxoso', array('ketqua' => $matches[3]));
        }
        else
        {
            echo 'Không có kết quả';
        }
    }

    public function actionLoDe()
    {
        $this->render('backend/admin/lode_setting');
    }

    public function actionNhapKetQuaLoDe()
    {
        $x80 = isset($_POST['x80']) ? $_POST['x80'] : '';
        $x8 = isset($_POST['x8']) ? $_POST['x8'] : '';
        $x3dot5 = isset($_POST['x3dot5']) ? $_POST['x3dot5'] : '';

        $today = (isset($_POST['date']) && $_POST['date'] !== '') ? $_POST['date'] : $today = date('Y-m-d');
        
        
        $ketquaxs = Ketquaxoso::model()->find('date= :date', array(':date' => $today));

        if ($ketquaxs)
        {
            $ketquaxs->x80 = json_encode(explode('-', $x80));
            $ketquaxs->x8 = json_encode(explode('-', $x8));
            $x3dot5Arr = explode('-', $x3dot5);
            sort($x3dot5Arr);
            $ketquaxs->x3dot5 = json_encode($x3dot5Arr);
            $ketquaxs->date = $today;
            $ketquaxs->last_update = date('Y-m-d H:i:s');
            if ($ketquaxs->update())
            {
                echo 'thành công';
            }
        }
        else
        {
            $ketquaxs = new Ketquaxoso();
            $ketquaxs->x80 = json_encode(explode('-', $x80));
            $ketquaxs->x8 = json_encode(explode('-', $x8));
            $x3dot5Arr = explode('-', $x3dot5);
            sort($x3dot5Arr);
            $ketquaxs->x3dot5 = json_encode($x3dot5Arr);
            $ketquaxs->date = $today;
            $ketquaxs->last_update = date('Y-m-d H:i:s');

            if ($ketquaxs->save())
            {
                echo 'thành công';
            }
        }
    }

    public function actionLayDuLieuLoDe()
    {
        $ketquaxs = Ketquaxoso::model()->findBySql("SELECT DATE_FORMAT(a.date,'%d/%m/%Y') as date, a.x80, a.x8, a.x3dot5 FROM ld_ketquaxoso a ORDER BY a.date DESC");
        $this->renderPartial('backend/admin/ketqua_xoso', array('model' => $ketquaxs));
    }

    public function actionLayKetQuaXoSoTuDong()
    {
        $today = date('d/m/Y');
        /*
          // Initialize the curl object
          $curl = curl_init();

          curl_setopt($curl, CURLOPT_URL, "http://www.xosothudo.com.vn/jquery/?option=com_main");
          curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

          $data = array(
          'results_date' => $today
          );

          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($curl, CURLOPT_POST, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

          $response = curl_exec($curl);
          curl_close($curl);
         */

        $postdata = http_build_query(
                array(
                    'results_date' => $today,
                )
        );

        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($opts);

        $response = file_get_contents('http://www.xosothudo.com.vn/jquery/?option=com_main', false, $context);

        $post = strrpos($response, "<table");

        if ($post)
        {
            $response = substr($response, $post);
            preg_match_all('/(<td>|<td style=(.*?)>)(.*?)<\/td>/', $response, $matches);
            $this->renderPartial('backend/admin/ketquaxoso', array('ketqua' => $matches[3]));

            // lưu DB
            //var_dump($matches[3]);
            $x80 = substr($matches[3][0], strlen($matches[3][0]) - 2);
            $arrX80 = array($x80);

            $arrX8 = str_split($x80, 1);

            $arrX3dot5 = explode('-', preg_replace('/\s+/', '', join('-', $matches[3])));
            for ($i = 0; $i < count($arrX3dot5); $i++)
            {
                $arrX3dot5[$i] = substr($arrX3dot5[$i], strlen($arrX3dot5[$i]) - 2);
            }
            sort($arrX3dot5);

            $today = date('Y-m-d');
            ;
            $ketquaxs = Ketquaxoso::model()->find('date= :date', array(':date' => $today));

            if ($ketquaxs)
            {
                $ketquaxs->x80 = json_encode($arrX80);
                $ketquaxs->x8 = json_encode($arrX8);
                $ketquaxs->x3dot5 = json_encode($arrX3dot5);
                $ketquaxs->date = $today;
                $ketquaxs->last_update = date('Y-m-d H:i:s');

                if ($ketquaxs->update())
                {
                    echo 'thành công';
                }
            }
            else
            {
                $ketquaxs = new Ketquaxoso();
                $ketquaxs->x80 = json_encode($arrX80);
                $ketquaxs->x8 = json_encode($arrX8);
                $ketquaxs->x3dot5 = json_encode($arrX3dot5);
                $ketquaxs->date = $today;
                $ketquaxs->last_update = date('Y-m-d H:i:s');
                if ($ketquaxs->save())
                {
                    echo 'thành công';
                }
            }
            $this->actionThongKeDanhSachThangGameLoDe();
        }
        else
        {
            echo 'Không có kết quả';
        }
    }

    public function actionThongKeDanhSachThangGameLoDe()
    {
        $ketquaHomNay = Ketquaxoso::layKetQuaXoSoHomNay();
        if ($ketquaHomNay)
        {
            $danhsachChoiHomNay = LoDe::layDanhSachLuotChoiHomNay();
            foreach ($danhsachChoiHomNay as $luotChoi)
            {
                $game = LoDeFactory::createGameLoDe($luotChoi->lode_type);
                $game->setChoices(json_decode($luotChoi->choices));
                $game->setBet($luotChoi->bet);

                $luotChoi->win_money = $game->calculateWinMoney($ketquaHomNay);
                $luotChoi->save();
            }
        }
    }

}
